package com.demo2.todo.service.impl;

import com.demo2.todo.exception.BadRequestException;
import com.demo2.todo.exception.ResourceNotFoundException;
import com.demo2.todo.model.dto.ShareResponse;
import com.demo2.todo.model.dto.TodoResponse;
import com.demo2.todo.model.entity.ShareTodo;
import com.demo2.todo.model.entity.Todo;
import com.demo2.todo.model.entity.User;
import com.demo2.todo.repository.ShareTodoRepository;
import com.demo2.todo.repository.TodoRepository;
import com.demo2.todo.repository.UserRepository;
import com.demo2.todo.service.SensitiveWordService;
import com.demo2.todo.service.ShareService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author evi
 */
@Service
@RequiredArgsConstructor
public class ShareServiceImpl implements ShareService {
    private final ShareTodoRepository shareTodoRepository;
    private final TodoRepository todoRepository;
    private final UserRepository userRepository;
    private final SensitiveWordService sensitiveWordService;

    @Override
    @Transactional
    public ShareResponse createShare(Long todoId, User user) {
        // 验证todo是否属于当前用户
        Todo todo = todoRepository.findByIdAndUser(todoId, user)
                .orElseThrow(() -> new ResourceNotFoundException("Todo not found"));

        // 敏感词自动审核
        boolean hasSensitiveWords = sensitiveWordService.containsSensitiveWords(todo.getContent());

        // 生成唯一分享码
        String shareCode = generateUniqueShareCode();

        ShareTodo shareTodo = new ShareTodo();
        shareTodo.setTodoId(todoId);
        shareTodo.setShareCode(shareCode);
        shareTodo.setExpiredAt(LocalDateTime.now().plusDays(7));

        // 设置审核状态：如果包含敏感词，需要管理员审核；否则自动通过
        if (hasSensitiveWords) {
            shareTodo.setReviewStatus(ShareTodo.ReviewStatus.pending);
            shareTodo.setPublic(false); // 未审核通过前不公开
        } else {
            shareTodo.setReviewStatus(ShareTodo.ReviewStatus.approved);
            shareTodo.setPublic(true); // 自动通过审核，直接公开
        }

        ShareTodo saved = shareTodoRepository.save(shareTodo);

        ShareResponse response = new ShareResponse();
        response.setShareCode(shareCode);
        response.setShareUrl("http://localhost:8080/share/" + shareCode);
        response.setExpiredAt(saved.getExpiredAt());
        response.setReviewStatus(saved.getReviewStatus().name());

        return response;
    }

    @Override
    public TodoResponse getSharedTodoByCode(String code) {
        ShareTodo shareTodo = shareTodoRepository.findByShareCode(code)
                .orElseThrow(() -> new ResourceNotFoundException("分享不存在或已过期"));

        // 检查是否过期
        if (shareTodo.getExpiredAt() != null &&
                shareTodo.getExpiredAt().isBefore(LocalDateTime.now())) {
            throw new BadRequestException("分享已过期");
        }

        Todo todo = todoRepository.findById(shareTodo.getTodoId())
                .orElseThrow(() -> new ResourceNotFoundException("任务不存在"));

        return mapToDto(todo);
    }

    // 生成唯一分享码
    private String generateUniqueShareCode() {
        String code;
        do {
            code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12);
        } while (shareTodoRepository.existsByShareCode(code));
        return code;
    }

    private TodoResponse mapToDto(Todo todo) {
        TodoResponse response = new TodoResponse();
        response.setId(todo.getId());
        response.setContent(todo.getContent());
        response.setStatus(todo.getStatus());
        response.setCreatedAt(todo.getCreatedAt());
        return response;
    }
}